import { Loading } from '@/global';
import { h, onMounted, reactive, ref, VNode } from 'vue';
import { FooterButtonOption, FooterButtonType } from '@/util/vnode_create_util/dynamic_dialog_creator';
import { ElButton } from 'element-plus/es';
import { ApiCode, ApiResult, Page } from '@/config/api_config/api_interface';

interface BusinessListGetMethodConfig<T, V, S>{
  params?: T;
  dataList: V[];
  apiMethod: (params: Page | T) => Promise<ApiResult<V[] | S[] | null>>,
  handleMethod?: (returnDataList: S[] | V[], dataList: V[]) => void
}
interface Slot{
  default: () => VNode | string; // 默认模板
  footer: () => VNode | string; // 底部的按钮模板
}
interface DialogMethodConfig<T> {
  width?: string | number; // 对话框宽度
  title: string; // 对话框标题
  slot: Slot;
  formData: T;
  isConfirm: boolean
}
// 表格加载等逻辑
export function commonTableListReactive<T, V, S> (config: BusinessListGetMethodConfig<T, V, S>) {
  const tableLoading = reactive<Loading>({ status: false });
  const page = reactive<Page>({ pageIndex: 1, pageLimit: 10 });
  const onLoad = () => {
    if (!tableLoading.status) {
      tableLoading.status = true;
      const params = config.params ? config.params : {};
      config.dataList.splice(0, config.dataList.length);
      config.apiMethod({ ...page, ...params }).then(res => {
        tableLoading.status = false;
        if (res.apiCode === ApiCode.Success) {
          if (res.result) {
            if (!config.handleMethod) {
              config.dataList.push(...res.result as V[]);
              console.log(config.dataList);
            } else {
              config.handleMethod(res.result, config.dataList);
            }
          }
        }
      }).catch(() => {
        tableLoading.status = false;
      });
    }
  };
  const mounted = onMounted(() => {
    onLoad();
  });
  return {
    tableLoading, onLoad, mounted, page
  };
}

// 对话框设置等逻辑
export function dialogCommonReactive<T> (config: DialogMethodConfig<T>) {
  const dialogVisible = ref(false);
  const title = ref('');
  const width = ref<string | number>('');
  const slot = reactive<Slot>({ default: () => <div></div>, footer: () => <div></div> });
  const confirmFooterConfig:FooterButtonOption[] = [
    { type: FooterButtonType.ok, buttonType: 'primary', label: '确定', action: () => {} },
    { type: FooterButtonType.cancel, buttonType: 'default', label: '取消', action: () => { dialogVisible.value = false; } }
  ];
  const createConfirmFooter = (formData: T, footerConfig: FooterButtonOption[]): () => VNode | string => {
    return () => <div>{footerConfig.map(item => <ElButton type={item.buttonType} onClick={e => item.action(formData)}>{item.label}</ElButton>)}</div>;
  };
  const openDialog = () => {
    dialogVisible.value = true;
    title.value = config.title;
    slot.footer = config.isConfirm ? createConfirmFooter(config.formData, confirmFooterConfig) : config.slot.footer;
    slot.default = config.slot.default;
  };
  return { dialogVisible, title, width, openDialog, slot };
}
